#ifndef MQTT_FILE_TRANSFER_H
#define MQTT_FILE_TRANSFER_H

#include <stdint.h>
#include <stdbool.h>
#include "connection/mqtt_client.h"

// 主题定义
#define TOPIC_FILE_META "file/transfer/meta"
#define TOPIC_FILE_DATA "file/transfer/data"
#define TOPIC_FILE_ACK "file/transfer/ack"
#define TOPIC_FILE_ERROR "file/transfer/error"

// 消息类型
typedef enum {
    MSG_TYPE_META = 0,
    MSG_TYPE_DATA = 1,
    MSG_TYPE_ACK = 2,
    MSG_TYPE_ERROR = 3
} msg_type_t;

// 默认配置
#define DEFAULT_CHUNK_SIZE 1024
#define DEFAULT_CLIENT_SEND_ID "mqtt_file_send_client"
#define DEFAULT_CLIENT_RECEIVER_ID "mqtt_file_receiver_client"
#define DEFAULT_RETRY_INTERVAL 1000 // 1秒
#define DEFAULT_MAX_RETRIES 3

// 文件元数据结构
typedef struct {
    char file_id[37]; // UUID格式
    char filename[256];
    size_t file_size;
    size_t chunk_size;
    int total_chunks;
} file_meta_t;

// 文件块结构
typedef struct {
    char file_id[37];
    int chunk_index;
    size_t chunk_size;
    uint8_t *data;
} file_chunk_t;

// ACK消息结构
typedef struct {
    char file_id[37];
    int chunk_index;
    int status; // 0=成功, 非0=错误码
} ack_message_t;

// 错误消息结构
typedef struct {
    char file_id[37];
    int error_code;
    char error_msg[256];
} error_message_t;

// 传输回调函数
typedef void (*transfer_progress_cb)(const char *file_id, int chunk_index, int total_chunks);
typedef void (*transfer_complete_cb)(const char *file_id, int status, const char *message);

// 文件传输上下文
typedef struct {
    neu_mqtt_client_t *mqtt_client;
    char *broker;
    int port;
    char *client_id;
    size_t chunk_size;
    transfer_progress_cb progress_cb;
    transfer_complete_cb complete_cb;
    void *user_data;
} file_transfer_ctx_t;

// API函数
file_transfer_ctx_t *file_transfer_create(const char *broker, int port, const char *client_id);
void file_transfer_destroy(file_transfer_ctx_t *ctx);
int file_transfer_send(file_transfer_ctx_t *ctx, const char *filename);
int file_transfer_receive(file_transfer_ctx_t *ctx, const char *save_path);
void file_transfer_set_callbacks(file_transfer_ctx_t *ctx,
                                 transfer_progress_cb progress_cb,
                                 transfer_complete_cb complete_cb,
                                 void *user_data);

// 工具函数
char *generate_file_id(void);
size_t get_file_size(const char *filename);
char *base64_encode(const uint8_t *data, size_t input_length);
uint8_t *base64_decode(const char *data, size_t input_length, size_t *output_length);

#endif // MQTT_FILE_TRANSFER_H
